//
//  PQConnection.m
//  ObjectivePQ
//
//  Created by Ian Michell on 30/06/2007.
//  Copyright 2007 Ian Michell. All rights reserved.
//

#import "PQConnection.h"
#import "DBStatement.h"
#import "DBPreparedStatement.h"
#import "PQPreparedStatement.h"
#import "PQStatement.h"

@interface PQStatement (Private)
- (id <DBStatement>) initStatementWithConnection: (PQConnection*) c;
@end

@implementation PQStatement (Private)
- (id <DBStatement>) initStatementWithConnection: (PQConnection*) c
{
	self = [super init];
	if (self)
	{
		self->conn = c;
		self->affectedRows = 0;
	}
	return self;
}
@end

@interface PQPreparedStatement (Private)
- (id <DBPreparedStatement>) initPreparedStatementWithConnection: (PQConnection*) c;
@end

@implementation PQPreparedStatement (Private)

- (id <DBPreparedStatement>) initPreparedStatementWithConnection: (PQConnection*) c
{
	self = [super init];
	self->conn = c;
	return self;
}

@end


@implementation PQConnection

- (id <DBConnection>) init 
{
	self = [super init];
	return self;
}

- (id <DBConnection>) initWithConnectionString: (NSString*) connStr
{
	self = [super init];
	if (self)
	{
		self->connectionStr = connStr;
	}
	return self;
}

- (void) connect
{
	// Connect to database with connection string
	self->connection = PQconnectdb([self->connectionStr cString]);
	if (![self isConnected])
		@throw [NSException exceptionWithName:@"PQConnectionException"
			reason:[[NSString alloc] initWithCString: PQerrorMessage(self->connection)]
			userInfo:nil];
}

- (void) connectWithConnectionString: (NSString*) connStr;
{
	self->connectionStr = connStr;
	[self connect];
}

- (void) setConnectionString: (NSString*) connStr
{
	self->connectionStr = connStr;
}

- (bool) isConnected
{
	if (PQstatus(self->connection) == CONNECTION_OK)
		return TRUE;
	
	return FALSE;
}

- (void) reset
{
	if (self->connection != nil)
		PQreset(self->connection);
	else 
	{
		@throw [NSException exceptionWithName:@"PQConnectionException"
			reason:@"You cannot reset a connection that doesn't exist!"
			userInfo:nil];
	}

}

- (void) close
{
	if (self->connection != nil)
		PQfinish(self->connection);
	else 
	{
		@throw [NSException exceptionWithName:@"PQConnectionException"
			reason:@"You cannot close a connection that doesn't exist!"
			userInfo:nil];
	}
}


- (id <DBStatement>) createStatement
{
	return [[PQStatement alloc] initStatementWithConnection: self];
}

- (id <DBPreparedStatement>)  prepareStatement
{
	return [[PQPreparedStatement alloc] initPreparedStatementWithConnection: self];
}

- (id <DBStatement>) createStatementWithQuery: (NSString*) query
{
	id <DBStatement> stmt = [[PQStatement alloc] initStatementWithConnection: self];
	[stmt setQuery: query];
	return stmt;
}

- (id <DBPreparedStatement>) prepareStatementWithQuery: (NSString*) query
{
	id <DBPreparedStatement> stmt = [[PQPreparedStatement alloc] initPreparedStatementWithConnection: self];
	[stmt setQuery: query];
	return stmt;
}


@end
